package com.ourfuture.junitdemo.demo17;

import static org.junit.Assert.assertNotNull;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;

import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.ext.mysql.MySqlConnection;
import org.junit.AfterClass;
import org.junit.BeforeClass;

public abstract class AbstratDbUnitTestCase {

	protected static Connection connection;
	protected static MySqlConnection dbunitConnection;

	@BeforeClass
	public static void setupDatabase() throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test");
		dbunitConnection = new MySqlConnection(connection, null);
	}

	protected IDataSet getDataSet(String name) throws Exception {
		InputStream inputStream = getClass().getResourceAsStream(name);
		assertNotNull("file" + name + " not found in classpath ", inputStream);
		Reader reader = new InputStreamReader(inputStream);
		FlatXmlDataSet dataset = new FlatXmlDataSet(reader);
		return dataset;
	}

	@AfterClass
	public static void closeDatabase() throws Exception {

		if (connection != null) {
			connection.close();
			connection = null;
		}

		if (dbunitConnection != null) {
			dbunitConnection.close();
			dbunitConnection = null;
		}
	}
}
